<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/6/8
 * Time: 14:59
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\web\middleware;

use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\SystemAdmin;
use Htlove\Jwt;

class Auth
{
    public function handle($request, \Closure $next)
    {
        $pathinfo = $request->pathinfo();
        if (preg_match('/login/', $pathinfo)) {
            return $next($request);
        }
        if (preg_match('/index/', $pathinfo)) {
            return $next($request);
        }
        //验证
        $access_token = $request->header('access_token');
        if (empty($access_token)) {
            return Show::json_show(Status::mini_noLogin, "请先登录");
        }
        $check = Jwt::getInstance()->verifyToken($access_token);

        if ($check === false) {
            return Show::json_show(Status::mini_error, "验证失败");
        }
        $request->s_id = $check['id'];
        //查询用户状态
        try {
            $admin = (new SystemAdmin())->getBaseById($check['id']);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_noLogin, "用户不存在");
        }
        if ($admin['status'] != 1) {
            return Show::json_show(Status::mini_noLogin, "登录失效！请重新登录");
        }
        if ($admin['type'] == 0) {
            $request->s_cate = 0;
        } else {
            $request->s_cate = $admin['machine_ids'];
        }

        return $next($request);
    }
}